<template>
  <div class="all-handle-box">
    <el-table
        :data="tableData"
        stripe
        style="width: 99%;height: 98%;margin-top: 2vh"
        border
        max-height="98%"
        empty-text="暂无数据"
    >
      <el-table-column
          fixed
          prop="finance_index"
          label="ID"
          width="60"
          align="center"
      />
      <el-table-column
          prop="total_money"
          label="报销总金额(元)"
          width="150"
          align="center"
      />
      <el-table-column
          prop="status"
          label="状态"
          align="center"
          width="120"
      >
        <template #default="{row}">
          <el-tag type="info" v-if="row.status === 0">已提交</el-tag>
          <el-tag type="warning" v-else-if="row.status === 1">审批中</el-tag>
          <el-tag type="success" v-else>已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="flow_uploader_name"
          label="申请人"
          width="150"
          align="center"
      />
      <el-table-column
          prop="bill_no"
          label="报销凭证编号"
          align="center"
          width="330"
      />
      <el-table-column
          prop="bill_date"
          label="原始单据日期"
          align="center"
          width="180"
      >
        <template #default="{row}">
          {{computeDate(row.bill_date)}}
        </template>
      </el-table-column>
      <el-table-column
          prop="enter_month"
          label="入账月份"
          align="center"
          width="120"
      >
        <template #default="{row}">
          {{row.enter_month}}月
        </template>
      </el-table-column>
      <el-table-column
          label="录入时间"
          width="180"
          align="center"
      >
        <template #default="{row}">
          {{sliceDate(row.created_at)}}
        </template>
      </el-table-column>
      <el-table-column
          prop="flow_operator_name"
          label="当前/最后审批人"
          align="center"
          width="150"
      />
      <el-table-column
          label="操作"
          align="center"
      >
        <template #default="{row}">
          <el-button
              type="primary"
              size="small"
              @click="showDetails(row.application_id)"
          >+
            操作
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <FinHandleDialog ref="handleRef" @reloadHandle="getPendingFlow"/>
</template>

<script setup>
import {ElTable, ElTableColumn, ElTag, ElButton, ElDialog, ElMessage} from "element-plus"
import {onMounted, reactive, ref} from "vue"
import {checkPendingFlow, checkUserByRole, getUptopHandle} from "@/api"
import emitter from "@/lib/eventBus.js"
import {useRoute} from "vue-router"
import Message from "@/lib/Message/Message"
import {getToHandle, getFinHandler} from "@/api/Finance/Bill"
import FinHandleDialog from "@/components/Finance/Bill/FinHandleDialog.vue"

const route = useRoute()

let user_info
const tableData = ref()
const handleDialogVisible = ref(false)
const handleRef = ref()
const options = ref([])
let detail_form = reactive({
  starting_date:'',
  termination_date:'',
  flow_detail:'',
  total_days:'',
  status:'',
  operator_name:'',
  copy_name:'',
})
const history_operator = ref([])

let upTop_id
let msg

onMounted(() => {
  getUserInfo()
  getUserList()
  getPendingFlow()
  // if(route && route.query.targetId){
  //   emitter.emit('update','to-handle')
  //   upTop_id = route.query.targetId
  //   msg = route.query.msg_id
  //   readMSG()
  // } else {
  //   getPendingFlow()
  // }
})

const getUserInfo = () => {
  user_info = JSON.parse(localStorage.getItem('syhyDocManSys'))
}

//获取级联用户列表
const getUserList = async () => {
  try {
    let rolename = []
    let roleUser = []
    const {data:res} = await getFinHandler()
    const values = res.data
    values.forEach(value => {
      let datas = Object.values(value)
      datas.forEach(data => {
        if(typeof data === "string"){
          rolename.push(data)
        } else {
          roleUser.push(data)
        }
      })
    })
    for (let i = 0; i < 2; i++){
      options.value.push({
        label:rolename[i],
        value:null,
        children:[]
      })
      for (let j = 0; j < roleUser[i].length; j++){
        options.value[i].children.push({
              label:roleUser[i][j].user_name,
              value:roleUser[i][j].user_id,
            }
        )
      }
    }
  } catch (e) {
    console.log(e)
  }
}

const getPendingFlow = async () => {
  try {
    console.log('getPendingFlowsuccess')
    tableData.value = []
    const {data:res} = await getToHandle({
      // const data = checkPendingFlow({
      userId : user_info.id
    })
    if(res.code === 200){
      tableData.value = res.data
    } else if (res.code === 201){
      return ElMessage({
        message:'暂无未审批的流程',
        type:'info'
      })
    } else {
      return ElMessage({
        message:'获取列表失败',
        type:'warning'
      })
    }
  } catch (e) {
    console.log(e)
  }
}


const computeDate = (date) => {
  return date.substring(0,10)
}

//已读消息
const readMSG = async () => {
  try {
    tableData.value = []
    const {data:res} = await getUptopHandle({
      userId:user_info.id,
      approve_id:upTop_id,
      msgId:msg
    })
    if (res.code === 200){
      tableData.value = res.data
    } else {
      getPendingFlow()
    }
  } catch (e) {
    console.log(e)
  }
}

const showDetails = (id) => {
  handleRef.value.showDetails(id)
}

const sliceDate = (utc_datetime) => {
  let new_datetime = utc_datetime.split("T")[0] + " " + utc_datetime.split("T")[1].split(".")[0]

  // 处理成为时间戳
  let timestamp = new Date(new_datetime.replace(/-/g, '/')).getTime()
  timestamp = timestamp / 1000
  // 增加8个小时，北京时间比utc时间多八个时区
  timestamp = timestamp + 8 * 60 * 60

  // 时间戳转为时间
  let date = new Date(parseInt(timestamp) * 1000)
  let YY = date.getFullYear() + '-'
  let MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  let DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
  let hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  let mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
  let ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
  return YY + MM + DD + " " + hh + mm + ss
}
</script>

<style scoped lang="less">
.all-handle-box{
  box-sizing: border-box;
  padding: 0 1vh;
  width: 91vw;
  height: 86.5vh;
  background-color: #fff;
}
</style>